<template>
    <div class="settings-page">
        <div class="container page">
            <div class="row">

            <div class="col-md-6 offset-md-3 col-xs-12">
                <h1 class="text-xs-center">Your Settings</h1>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
                    <el-form-item label="头像地址" prop="image">
                        <el-input v-model="ruleForm.image" placeholder="URL of profile picture"></el-input>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="ruleForm.username" placeholder="Your Name"></el-input>
                    </el-form-item>
                    <el-form-item label="简介" prop="bio">
                        <el-input type="textarea" v-model="ruleForm.bio" placeholder="Short bio about you"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="ruleForm.email" placeholder="Email"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="ruleForm.password" placeholder="Password"></el-input>
                    </el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">
                        Update Settings
                    </el-button>
                </el-form>
            </div>

            </div>
        </div>
        </div>
</template>

<script>
import { mapState } from 'vuex'

import { updateUser } from '@/api/user'

// 仅在客户端加载 js-cookie 包
const Cookie = process.client ? require('js-cookie') : undefined

  export default {
    name: 'Settings',
    middleware: 'authenticated',
    computed: {
      ...mapState(['user'])
    },
    asyncData (context) {
        const user = context.store.state.user
        return {
            ruleForm: {
                image: user.image,
                username: user.username,
                bio: user.bio,
                email: user.email,
                password: ''
            },
            rules: {
                image: [
                    { required: true, message: '请输入头像地址', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ]
            },
            submitLoading: false
        }
        
    },
    methods: {
        submitForm() {
            this.$refs['ruleForm'].validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true;
                    try{
                        const { data } = await updateUser({
                            user: this.ruleForm
                        })
                        //console.log(data)
                        // 保存用户的登录状态
                        this.$store.commit('setUser', data.user)

                        // 为了防止刷新页面数据丢失，我们需要把数据持久化
                        Cookie.set('user', data.user)

                        this.$router.push('/')
                    }catch(error) {
                        //console.dir(err)
                        let msg = ``
                        const errorObj = error.response.data.errors;
                        Object.keys(errorObj).forEach((item) => {
                            msg += `${item}：${errorObj[item][0]}<br/>`
                        })
                        this.$message({
                            type: 'error',
                            dangerouslyUseHTMLString: true,
                            message: msg
                        })
                        this.submitLoading = false;
                    }
                }
            })
        }
    }
  }
</script>